import 'dart:async';

import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:get/get.dart';

import 'package:flutter_deer/res/colors.dart';
import 'package:flutter_deer/util/ip_utils.dart';
import 'package:flutter_deer/util/socket/mdc_provider.dart';
import 'package:flutter_deer/util/toast_utils.dart';
import 'package:flutter_deer/widgets/dialog/add_mdc_dialog.dart';
import 'package:flutter_deer/widgets/press_blue_button.dart';

class SettingPage4Mdc extends StatefulWidget {
  const SettingPage4Mdc({super.key});

  @override
  State<SettingPage4Mdc> createState() => _SettingPage4MdcState();
}

class _SettingPage4MdcState extends State<SettingPage4Mdc> {
  late RxList<MdcSetBean> _mdcList;
  final mdcProvider = Get.find<MdcProvider>();
  final List<GlobalKey> _itemKeys = []; // 用于存储每个item的key
  final RxString _ip = ''.obs;
  StreamSubscription<MapEntry<String, bool>>? _subscription;

  @override
  void initState() {
    super.initState();

    _mdcList = mdcProvider.mdcList;

    // 初始化key列表
    _itemKeys.clear();
    for (int i = 0; i < _mdcList.length; i++) {
      _itemKeys.add(GlobalKey());
    }

    // 获取当前ip地址
    IpUtils.getLocalIpAddress().then((value) {
      _ip.value = value ?? '';
    });

    // 监听渲染结束
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _subscription = mdcProvider.mdcStateStream.listen((event) {
        for (final value in _mdcList) {
          if ('${value.ip}:${value.port}' == event.key) {
            if (value.connected != event.value) {
              setState(() {
                value.connected = event.value;
              });
            }
          }
        }
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _subscription?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Obx(() => Scaffold(
          appBar: AppBar(
            title: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('当前IP:\t\t\t${_ip.value}', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.normal, color: Colours.text)),
                if (_mdcList.length < 5) PressBlueButton(text: ' 添 加 ', onPressed: () => _showAddMdcDialog(null)),
              ],
            ),
          ),
          body: GridView.builder(
            gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: 350, // 每个item最大宽度100
              mainAxisSpacing: 10, // 垂直间距
              crossAxisSpacing: 10, // 水平间距
              childAspectRatio: 2.5, // 宽高比 = width/height = 480/200 = 2.5
            ),
            padding: const EdgeInsets.all(8.0),
            itemCount: _mdcList.length,
            itemBuilder: (context, index) {
              final item = _mdcList[index];
              return _buildMdcItem(item, index);
            },
          ),
        ));
  }

  /// 构建MDC项
  Widget _buildMdcItem(MdcSetBean item, int index) {
    // 确保key列表大小与数据列表一致
    if (_itemKeys.length <= index) {
      _itemKeys.add(GlobalKey());
    }

    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 5, vertical: 5),
      shape: RoundedRectangleBorder(
        side: BorderSide(color: Colors.blue.shade700, width: 1),
        borderRadius: BorderRadius.circular(8),
      ),
      child: InkWell(
        onTap: () {
          _showPopupMenu(context, item, index);
        },
        child: Container(
          padding: const EdgeInsets.all(16),
          child: Stack(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const SizedBox(height: 1),
                  Row(
                    children: [
                      const SizedBox(width: 55),
                      Expanded(child: Text('IP:${item.ip}', style: const TextStyle(fontWeight: FontWeight.bold))),
                    ],
                  ),
                  const SizedBox(height: 15),
                  Text('端口:${item.port}'),
                  const SizedBox(height: 5),
                  Text(item.needLevelGauge ? '获取液位仪数据-开启' : '获取液位仪数据-关闭'),
                ],
              ),
              // 状态标签
              Positioned(
                top: 0,
                left: 0,
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 3),
                  decoration: BoxDecoration(color: item.connected ? Colors.green : Colors.red, borderRadius: BorderRadius.circular(3)),
                  child: Text(key: _itemKeys[index], item.connected ? '正常' : '异常', style: const TextStyle(color: Colors.white, fontSize: 12)),
                ),
              ),
              // 设置图标
              Positioned(top: 8, right: 0, child: Icon(Icons.settings, color: Colors.grey.shade600)),
              // 设置图标
              Positioned(bottom: 6, right: 2, child: Icon(Icons.router, color: Colors.blue.shade700, size: 30)),
            ],
          ),
        ),
      ),
    );
  }

  /// 显示弹出菜单
  void _showPopupMenu(BuildContext context, MdcSetBean item, int index) {
    final RenderBox overlay = Overlay.of(context).context.findRenderObject() as RenderBox;

    // 获取当前点击项的全局坐标和大小
    final RenderBox target = _itemKeys[index].currentContext!.findRenderObject() as RenderBox;
    final Offset targetPosition = target.localToGlobal(Offset.zero);
    final Size targetSize = target.size;

    // 计算弹出菜单显示位置（目标组件正下方）
    final double dx = targetPosition.dx; // X坐标与目标组件左对齐
    final double dy = targetPosition.dy + targetSize.height; // Y坐标在目标组件下方

    showMenu(
      popUpAnimationStyle: AnimationStyle.noAnimation,
      context: context,
      position: RelativeRect.fromRect(
        Rect.fromLTWH(dx + targetSize.width + 100, dy, targetSize.width, 0),
        Offset.zero & overlay.size, // overlay大小
      ),
      items: [
        PopupMenuItem(child: const Text('删除'), onTap: () => _checkMdcPassword(item, () => _deleteMdc(item))),
        // const PopupMenuItem(child: Text('更新配置')),
        // const PopupMenuItem(child: Text('时间同步')),
        PopupMenuItem(
          child: const Text('TTC回调'),
          onTap: () {
            _checkMdcPassword(item, () {
              _showMdcCallbackDialog(item);
            });
          },
        ),
      ],
    );
  }

  /// 验证密码
  void _checkMdcPassword(MdcSetBean item, VoidCallback onSuccess) {
    // 在调试模式下直接通过
    if (true) {
      // 替换为实际的调试检查
      onSuccess();
      return;
    }

    // 显示密码输入对话框
    _showPasswordDialog(onSuccess);
  }

  /// 显示密码输入对话框
  void _showPasswordDialog(VoidCallback onSuccess) {
    final passwordController = TextEditingController();
    showDialog<void>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('请输入实施操作密码'),
          content: TextField(
            controller: passwordController,
            obscureText: true,
            decoration: const InputDecoration(hintText: '请输入密码'),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                if (passwordController.text == '202323') {
                  Navigator.of(context).pop();
                  onSuccess();
                } else {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('密码错误，请联系管理员')),
                  );
                }
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  /// 显示添加MDC对话框
  void _showAddMdcDialog(MdcSetBean? item) {
    showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return AddMdcDialog(item: item, onAdd: _addMdc);
      },
    );
  }

  /// 添加MDC
  void _addMdc(MdcSetBean mdcSetBean) {
    if (_mdcList.any((element) => element.ip == mdcSetBean.ip && element.port == mdcSetBean.port)) {
      Toast.show('IP地址和端口已存在');
      return;
    }
    _mdcList.add(mdcSetBean);
    // 保存配置
    SpUtil.putObjectList(Constant.mdcSetBeanList, _mdcList);
    // 将新的MDC添加到列表中并更新UI
    mdcProvider.addMdcHub(mdcSetBean);

    if (Navigator.of(context).canPop()) {
      Navigator.of(context).pop();
    }
  }

  /// 删除MDC
  void _deleteMdc(MdcSetBean mdcSetBean) {
    // 实现删除逻辑
    _mdcList.remove(mdcSetBean);
    // 保存配置
    SpUtil.putObjectList(Constant.mdcSetBeanList, _mdcList);
    // 从列表中移除MDC并更新UI
    mdcProvider.removeMdcHub(mdcSetBean);
  }

  /// 显示MDC回调对话框
  void _showMdcCallbackDialog(MdcSetBean item) {
    // 实现TTC回调对话框
    Toast.show('暂不支持');
  }
}

//MdcSetBean数据类
class MdcSetBean {
  MdcSetBean({
    this.linkType = -1,
    this.ip = '',
    this.port = 0,
    this.needLevelGauge = false,
    this.connected = false,
  });

  factory MdcSetBean.fromJson(Map<String, dynamic> json) => MdcSetBean(
        ip: (json['ip'] is String) ? json['ip'] as String : '',
        port: (json['port'] is int) ? json['port'] as int : -1,
        linkType: (json['linkType'] is int) ? json['linkType'] as int : -1,
        needLevelGauge: json['needLevelGauge'] == true,
        connected: json['connected'] == true,
      );

  final int linkType;
  final String ip;
  final int port;
  final bool needLevelGauge;
  bool connected;

  Map<String, dynamic> toJson() => {
        "linkType": linkType,
        "ip": ip,
        "port": port,
        "needLevelGauge": needLevelGauge,
        "connected": connected,
      };

  // 存储配置
  static void saveMdcSetBeanList(List<MdcSetBean> list) {
    SpUtil.putObjectList(Constant.mdcSetBeanList, list);
  }

  // 读取配置
  static List<MdcSetBean> getMdcSetBeanList() {
    final jsonList = SpUtil.getObjList<MdcSetBean>(
      Constant.mdcSetBeanList,
      (json) => MdcSetBean.fromJson(json as Map<String, dynamic>),
    );
    return jsonList ?? [];
  }
}
